#!/bin/bash
work_dir=$(cd $(dirname $0);pwd)
basic_dir=$(cd $work_dir;cd ..;pwd)
cd $basic_dir

usage(){
  echo "Usage: sh $0 start|stop|status|restart|version"
}

version(){
  cat conf/app-meta.inf
  echo "" 
}

status(){
  if [[ -f bin/app.pid ]] && [[ -n $(ps -e|grep -w $(cat bin/app.pid)|grep -v grep) ]]; then
    echo "app is running,pid $(cat bin/app.pid)"
  else
    echo "app not running"
  fi
}

start(){
  if [[ -f bin/app.pid ]] && [[ -n $(ps -e|grep -w $(cat bin/app.pid)|grep -v grep) ]]; then
    echo "already started,pid $(cat bin/app.pid)"  
  else 
    nohup bin/bootstrap >> logs/console.log 2>&1 &
    echo $! > bin/app.pid
    echo "starting ...,pid $(cat bin/app.pid)"  
  fi
}

stop(){
  [[ ! -f bin/app.pid ]] && return 1
  cat bin/app.pid|xargs -i kill {} >/dev/null 2>&1 &
  local stop_pid=$!
  local app_pid=$(cat bin/app.pid)
  local cnt=0
  while [[ -n $stop_pid ]] 
  do
    [[ $cnt -gt 3 ]] && break
    echo "waiting stop $(cat bin/app.pid) ..." 
    sleep 1
    cnt=$(expr $cnt + 1) 
    stop_pid=$(ps|grep $stop_pid|grep -v grep|awk '{print $1}') 
  done 
  if [[ -n $(ps -e|grep -w $app_pid|grep -v grep) ]]; then
    kill -9 $app_pid > /dev/null 2>&1
  fi
  rm -f bin/app.pid
}

main(){
  local CMD=$1
  [ -z $CMD ] && CMD='start' 
  case $CMD in
       'start')
          start
          ;;
       'stop')
          stop
          ;;
       'status')
          status
          ;;
       'restart')
          stop
          start
          ;;
       'version')
          version
          ;;
       *)
          usage
          ;;
  esac
}


main $1

